package com.dk.filter;

import com.alibaba.fastjson.JSONObject;
import com.dk.data.Result;
import com.dk.em.ConstantEnum;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName LoginFilter 登录的过滤器
 * @Deacription TODO
 * @Author hqq
 * @Date 2021/10/25 17:37
 * @Version 1.0
 **/
@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 配置过滤类型，有四种不同生命周期的过滤器类型
     * 1. pre：路由之前
     * 2. routing：路由之时
     * 3. post：路由之后
     * 4. error：发送错误调用
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }
    //网关可以写多个过滤器.这个表示过滤器执行的顺序,数字越小,越先执行
    @Override
    public int filterOrder() {
        return 1;
    }
    //过滤器的开关
    @Override
    public boolean shouldFilter() {
        RequestContext  ctx =RequestContext.getCurrentContext();//判断上一层拦截是否通过
        if(!ctx.sendZuulResponse()){//上一层拦截不通过
            System.out.println(" 上一层拦截不通过,不开启拦截");//该拦截不需要开启
            return false;
        }
        return true;
    }
    @Override
    public Object run() throws ZuulException {
        //1.获取当前线程请求上下文类
        RequestContext currentContext = RequestContext.getCurrentContext();
        //2.获取request域对象
        HttpServletRequest request = currentContext.getRequest();
        //3.通过请求头获取到token值
        String token = request.getHeader("token"); //括号里的可以自定义,但是要和前台传进来的保持一致
        StringBuffer requestURL = request.getRequestURL();
        System.out.println("111"+requestURL);
        String requestURI = request.getRequestURI();
        System.out.println("222"+requestURI);
        if(token == null || "".equals(token) || !redisTemplate.hasKey(token)){
            //设置响应域对象
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(400);
            //获取response
            HttpServletResponse response = currentContext.getResponse();
            try {
                response.setContentType("text/html;charset=utf-8");
                Result result = Result.bulid(ConstantEnum.NO_AUTH).setResult("用户未登录，无法访问服务,请先登录");
                response.getWriter().write(JSONObject.toJSONString(result));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
